/**
 * 精简的请求频率限制器
 * 只保留基本的并发控制
 */
class RateLimiter {
  constructor(options = {}) {
    this.maxConcurrentRequests = options.maxConcurrentRequests || 5;
    this.queueTimeout = options.queueTimeout || 10000;
    
    // 当前活跃请求
    this.activeRequests = new Map(); // URL -> Promise
    this.requestCount = 0;
  }

  /**
   * 处理请求
   */
  async processRequest(url, requestHandler) {
    // 检查是否有相同URL的活跃请求，如果有就等待
    if (this.activeRequests.has(url)) {
      try {
        return await this.activeRequests.get(url);
      } catch (error) {
        // 如果现有请求失败，继续处理新请求
      }
    }

    // 检查并发数限制
    if (this.activeRequests.size >= this.maxConcurrentRequests) {
      // 等待有请求完成
      await this.waitForSlot();
    }

    // 执行请求
    const requestPromise = this.executeRequest(requestHandler);
    this.activeRequests.set(url, requestPromise);
    
    try {
      return await requestPromise;
    } finally {
      this.activeRequests.delete(url);
    }
  }

  /**
   * 等待有空闲槽位
   */
  async waitForSlot() {
    const timeout = setTimeout(() => {
      throw new Error('请求队列超时');
    }, this.queueTimeout);

    // 等待任意一个请求完成
    if (this.activeRequests.size > 0) {
      try {
        await Promise.race(Array.from(this.activeRequests.values()));
      } catch (error) {
        // 忽略单个请求的错误，只要有请求完成就继续
      }
    }
    
    clearTimeout(timeout);
  }

  /**
   * 执行实际请求
   */
  async executeRequest(requestHandler) {
    this.requestCount++;
    return await requestHandler();
  }

  /**
   * 获取统计信息
   */
  getStats() {
    return {
      activeRequestsCount: this.activeRequests.size,
      totalRequests: this.requestCount
    };
  }
}

module.exports = RateLimiter;